/**
 * @Author: gan
 * @Description: 用户API
 * @File:  admin
 * @Version: 1.0.0
 * @Date: 2022/4/8 4:53 下午
 */

package admin

import (
	"gin-canteen-src/enums"
	"gin-canteen-src/global"
	"gin-canteen-src/model/admin"
	"gin-canteen-src/model/admin/request"
	commonRequest "gin-canteen-src/model/common/request"
	commonResponse "gin-canteen-src/model/common/response"
	"gin-canteen-src/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type UserApi struct{}

// @Title  登录
// @Description  描述
// @Author gan
func (s *UserApi) Login(c *gin.Context) {
	var l request.Login
	_ = c.ShouldBindJSON(&l)
	u := &admin.User{Username: l.Username, Password: l.Password}
	if err := utils.Verify(l, utils.LoginVerify); err != nil {
		commonResponse.FailWithMessage(enums.InvalidParams, err.Error(), c)
		return
	}
	if err, user := userService.Login(u); err != nil {
		global.GloLogger.Error("登陆失败! 用户名不存在或者密码错误!", zap.Error(err))
		commonResponse.FailWithMessage(enums.ERROR, "用户名不存在或者密码错误", c)
	} else {
		// 生成jwt
		userService.MakeToken(c, user)
	}
}

// @Title  创建账号
// @Description  描述
// @Author gan
func (s *UserApi) Create(c *gin.Context) {
	var l admin.User
	_ = c.ShouldBindJSON(&l)
	if err := utils.Verify(l, utils.RegisterVerify); err != nil {
		commonResponse.FailWithMessage(enums.InvalidParams, err.Error(), c)
		return
	}
	if err, id := userService.Create(&l); err != nil {
		global.GloLogger.Error("用户创建失败!", zap.Error(err))
		commonResponse.FailWithMessage(enums.ERROR, "用户创建失败", c)
	} else {
		commonResponse.OkWithDetailed(id, "OK", c)
	}
}

// @Title  用户列表
// @Description  描述
// @Author gan
func (s *UserApi) GetUserList(c *gin.Context) {
	var pageInfo commonRequest.PageInfo
	_ = c.ShouldBindJSON(&pageInfo)
	if err := utils.Verify(pageInfo, utils.PageInfoVerify); err != nil {
		commonResponse.FailWithMessage(enums.ERROR, err.Error(), c)
		return
	}
	if list, total, err := userService.GetUserList(pageInfo); err != nil {
		global.GloLogger.Error("获取失败!", zap.Error(err))
		commonResponse.FailWithMessage(enums.ERROR, "获取失败", c)
	} else {
		commonResponse.OkWithDetailed(commonResponse.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	}
}
